from django.db import models
from django.core.exceptions import ValidationError
from django.utils import timezone
from datetime import datetime
from base import models as baseModels
# Create your models here.
class ProductOrderModel(models.Model):
    '''生产信息'''
    orderId = models.CharField(max_length=50, verbose_name='指令单号', default='',null=False,  # 数据库层面不允许为NULL
        blank=True,unique=True)
    date = models.DateField(verbose_name='下达日期', default=timezone.now)
    # # 将原来的standard字符字段改为外键关联到StandardModel
    finished = models.ForeignKey(
        baseModels.FinishedModel,
        on_delete=models.PROTECT,
        null=False,  # 数据库层面不允许为NULL
        blank=False,
        verbose_name='生产品种',
    )
    batch_number = models.CharField(max_length=50, verbose_name='批号', default=None, null=False,  # 数据库层面不允许为NULL
                                    blank=False)
    STATE_CHOICES = [
        ("1", "保存"),
        ("0", "暂存"),
    ]
    state = models.CharField(max_length=50, verbose_name='状态', default='0', choices=STATE_CHOICES)
    # 创建时间：首次保存时自动设置为当前时间，之后不会更新
    # create_at = models.DateTimeField(verbose_name='创建日期', auto_now_add=True)

    create_at = models.DateTimeField(verbose_name='创建日期',default=timezone.now ) # 默认为当前时间
    # 更新时间：每次保存（包括首次）时自动更新为当前时间
    update_at = models.DateTimeField(verbose_name='更新日期', auto_now=True)
    class Meta:
        verbose_name='生产排产'
        verbose_name_plural = '生产排产'  # 自定义复数形式，与单数相同

    def __str__(self):
        return '|'.join([self.orderId,self.finished.name])
    def clean(self):
        """模型验证方法，用于检查保存条件"""
        try:
            if not self.id: #新增

                if not self.orderId:


                    id_date=datetime.now()
                    if self.date:
                       id_date=self.date
                    orderIdList=ProductOrderModel.objects.filter(orderId__startswith=f'{id_date.strftime("%Y%m%d")}').order_by('-orderId').values_list('orderId',flat=True).first()

                    if orderIdList:
                        try:
                            result=orderIdList[:7]+str(int(orderIdList[7:])+1).zfill(4)
                        except:
                            raise ValidationError({"orderId": '指令单号检验失败'})
                    else:
                        result=id_date.strftime('%Y%m%d')+'0001'
                    # print(raw)
                    self.orderId=result

            try:
                 if len(self.orderId) == 12:
                   int(self.orderId[7:])
                 else:
                    raise ValidationError({"orderId": '指令单号检验失败,订单编号只能保留12位'})
            except:
                 raise ValidationError({"orderId": '指令单号检验失败,订单编号格式不对'})




        except Exception as e:

            raise ValidationError(e)

class ProductOrderOfIntermediateModel(models.Model):
    '''中间品生产信息'''
    orderId = models.CharField(max_length=50, verbose_name='指令单号', default='',null=False,  # 数据库层面不允许为NULL
        blank=True,unique=True)
    date = models.DateField(verbose_name='下达日期', default=timezone.now)
    # # 将原来的standard字符字段改为外键关联到StandardModel
    finished = models.ForeignKey(
        baseModels.IntermediateModel,
        on_delete=models.PROTECT,
        null=False,  # 数据库层面不允许为NULL
        blank=False,
        verbose_name='生产品种',
    )
    batch_number = models.CharField(max_length=50, verbose_name='批号', default=None, null=False,  # 数据库层面不允许为NULL
                                    blank=False)
    STATE_CHOICES = [
        ("1", "保存"),
        ("0", "暂存"),
    ]
    state = models.CharField(max_length=50, verbose_name='状态', default='0', choices=STATE_CHOICES)
    # 创建时间：首次保存时自动设置为当前时间，之后不会更新
    # create_at = models.DateTimeField(verbose_name='创建日期', auto_now_add=True)

    create_at = models.DateTimeField(verbose_name='创建日期',default=timezone.now ) # 默认为当前时间
    # 更新时间：每次保存（包括首次）时自动更新为当前时间
    update_at = models.DateTimeField(verbose_name='更新日期', auto_now=True)
    class Meta:
        verbose_name='生产排产(中间品)'
        verbose_name_plural = '生产排产(中间品)'  # 自定义复数形式，与单数相同

    def __str__(self):
        return '|'.join([self.orderId,self.finished.name])
    def clean(self):
        """模型验证方法，用于检查保存条件"""
        try:
            if not self.id: #新增

                if not self.orderId:


                    id_date=datetime.now()
                    if self.date:
                       id_date=self.date
                    orderIdList=ProductOrderOfIntermediateModel.objects.filter(orderId__startswith=f'{id_date.strftime("%Y%m%d")}').order_by('-orderId').values_list('orderId',flat=True).first()

                    if orderIdList:
                        try:
                            result=orderIdList[:7]+str(int(orderIdList[7:])+1).zfill(4)
                        except:
                            raise ValidationError({"orderId": '指令单号检验失败'})
                    else:
                        result=id_date.strftime('%Y%m%d')+'0001'
                    # print(raw)
                    self.orderId=result

            try:
                 if len(self.orderId) == 12:
                   int(self.orderId[7:])
                 else:
                    raise ValidationError({"orderId": '指令单号检验失败,订单编号只能保留12位'})
            except:
                 raise ValidationError({"orderId": '指令单号检验失败,订单编号格式不对'})




        except Exception as e:

            raise ValidationError(e)